//
//  ViewController.m
//  蓝牙
//
//  Created by MyMac on 15/9/8.
//  Copyright (c) 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
//中端uuidgen
static NSString*const serverUUIDStr=@"C3A8D954-4268-4416-BBF3-42BCC1D57AC6";
static  NSString*const characterUUIDStr=@"2DEFE2CD-70EE-4D6D-8E29-03670495D846";
@interface ViewController ()<CBPeripheralManagerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIButton *image;
@property (weak, nonatomic) IBOutlet UIButton *text;
@property(nonatomic,strong)CBPeripheralManager*manager;
@property(nonatomic,strong)CBMutableService*service;
@property(nonatomic,strong)CBMutableCharacteristic*characteristic;
@property(nonatomic,strong)CBCentral*center;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _manager=[[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)imageClick:(id)sender {
    UIImage*image=[UIImage imageNamed:@"333"];
    NSData*data=UIImagePNGRepresentation(image);
    self.characteristic.value=data;
    [self.manager updateValue:data forCharacteristic:self.characteristic onSubscribedCentrals:@[self.center]];
    
    
}
- (IBAction)textClick:(id)sender {
    
    NSString*message=@"哈哈哈哈哈哈😄";
    NSData*data=[message dataUsingEncoding:NSUTF8StringEncoding];
    self.characteristic.value=data;
    [self.manager updateValue:data forCharacteristic:self.characteristic onSubscribedCentrals:@[self.center]];
}
//-(CBPeripheralManager*)manager{
//    if(!_manager){
//        _manager=[[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
//    
//    }
//
//    return _manager;
//
//
//}
//检验周边管理者的状态，在这检测设备是否支持该版本蓝牙
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    //每个服务CBMutableService由不同的特征CBMutableCharacteristic组成
    
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"设备支持蓝牙");
            [self setupServer];
        break;
            
        default:
            NSLog(@"设备不支持当前蓝牙版本");
            break;
    }
}

-(void)setupServer
{
 //每一个服务和特征都需要用一个128bit或16bit的UUID去标示
    CBUUID*serverUUID=[CBUUID UUIDWithString:serverUUIDStr];
    self.service=[[CBMutableService alloc]initWithType:serverUUID primary:YES];
    CBUUID*characterUUID=[CBUUID UUIDWithString:characterUUIDStr];
    //第一个参数是给特征绑定一个标识符，第二个参数是决定特征怎么使用，第三个参数传nil表示待会会给特征赋一个值，在这赋也可以，最后一个参数是属性的读，写，加密，权限操作,要想实现双向通信，必须实现这里
    self.characteristic=[[CBMutableCharacteristic alloc]initWithType:characterUUID properties:CBCharacteristicPropertyNotify|CBCharacteristicPropertyRead|CBCharacteristicPropertyWrite|CBCharacteristicPropertyWriteWithoutResponse value:nil permissions:CBAttributePermissionsReadable|CBAttributePermissionsWriteable];
    //为服务设置一些特征，一个服务可以有多个特征，一个周边设备可以有多个服务
    self.service.characteristics=@[self.characteristic];
    NSLog(@"给服务增加特征");
   //为周边管理者添加服务，一旦完成这一步，将会通知他的代理
    [self.manager addService:self.service];
    NSLog(@"给周边增加服务");

}
//添加完服务后的代理
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{

    if(error==nil){
        NSLog(@"周边增加服务成功");
    //如果添加服务没有错，就可以开始广播服务了
        NSDictionary*dict=@{CBAdvertisementDataLocalNameKey :
                                 @"LJ的广播", CBAdvertisementDataServiceUUIDsKey :
                                 @[[CBUUID UUIDWithString:serverUUIDStr]]};
        [self.manager startAdvertising:dict];
        NSLog(@"正在增加广播");
    
    
    }else {
        NSLog(@"周边管理者添加服务失败");
    }


}
//开始广播
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{
    if(error==nil){
    NSLog(@"开始广播");
    }else{
    NSLog(@"广播失败:%@",error);
    
    }


}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
    NSLog(@"接收到连接(阅读 )周边的请求");

}
//中央连接后，调用，在这里给中央发送动态数据
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic;
{
    
    self.center=central;
    NSLog(@"连接到了周边，，，正准备给中央传送数据");
    //发送数据
    NSString*message=@"我是周边广播，，，你好";
    NSData*data=[message dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.manager updateValue:data forCharacteristic:self.characteristic onSubscribedCentrals:@[central]];
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"中央移除了通知，，或中央断开了连接");

}
- (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary *)dict
{
    NSLog(@"状态恢复");

}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{

    //蓝牙通信，中央对周边既可读也可写
    //对周边进行xie的操作，就是与可穿戴设备连接的方式，控制可穿戴设备
    NSLog(@"收到中央写的请求");
    for(CBATTRequest*req in requests){
        NSString*Writestr=[[NSString alloc]initWithData:req.value encoding:NSUTF8StringEncoding];
        self.label.text=Writestr;
        NSLog(@"周边收到写的请求%@",Writestr);
    }

}
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral
{
    NSLog(@"peripheralManagerIsReadyToUpdateSubscribers");

}

@end
